#include <stdio.h>
#ifdef WIN32
#include "windows.h"
#endif
#include <GL/gl.h>
#include <GL/glut.h>
#include "bmp_loader.h"

GLuint textureID = -1;

struct Vertex
{
    float tu, tv;
    float x, y, z;
};

Vertex g_quadVertices[] =
{
    { 0.0f,0.0f, -1.0f,-1.0f, 0.0f },
    { 1.0f,0.0f,  1.0f,-1.0f, 0.0f },
    { 1.0f,1.0f,  1.0f, 1.0f, 0.0f },
    { 0.0f,1.0f, -1.0f, 1.0f, 0.0f }
};

void glutResize(int width, int height)
{
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
      /* modify this line to change perspective values */
	gluPerspective(45.0, (float)width/(float)height, 1.0, 300.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void glutDisplay(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glTranslatef( 0.0f, 0.0f, -3.0f );

	glEnable(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D,textureID);

    glInterleavedArrays( GL_T2F_V3F, 0, g_quadVertices );
    glDrawArrays( GL_QUADS, 0, 4 );


    glFlush();
    glutSwapBuffers();
}


void Init()
{
#ifdef WIN32
	BmpData *imageData = BmpLoader("../../src/duck.bmp");
#else
	BmpData *imageData = BmpLoader("src/duck.bmp");
#endif

	glGenTextures(1, &textureID);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

	glBindTexture(GL_TEXTURE_2D, textureID);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, imageData->width, imageData->height, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData->data);

	//Specify Filtering
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	BmpFree(imageData);

}


int main(int argc, char** argv)
{
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA | GLUT_MULTISAMPLE );
    glutInitWindowPosition( 100, 100 );
    glutInitWindowSize( 300, 300 );
    glutInit( &argc, argv );

    glutCreateWindow("simpleogl");

	Init();

	glutReshapeFunc(glutResize);
	glutDisplayFunc(glutDisplay);

	glutMainLoop();
}
